iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
自我挑戰組

LeetCode 每日任務系列 第 23

LeetCode Day23

  • 分享至 

  • xImage
  •  

3. Longest Substring Without Repeating Characters

題目:
找出字串中不含重複字元的最長子字串長度

範例:

  • 兒Example 1:
    Input: s = "abcabcbb"
    Output: 3
    Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.

  • Example 2:
    Input: s = "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.

  • Example 3:
    Input: s = "pwwkew"
    Output: 3
    Explanation: The answer is "wke", with the length of 3.
    Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.


想法:
典型解法:滑動視窗 + 雙指標

  • 碰到重複字元時,要正確地更新 left 位置
  • 每次更新 maxLen 時使用 right - left + 1

程式碼:

import java.util.HashMap;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        int maxLen = 0;
        int left = 0; // 視窗左邊界

        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);

            // 如果字元重複且在目前視窗內
            if (map.containsKey(c) && map.get(c) >= left) {
                // 將左邊界移到重複字元的下一個位置
                left = map.get(c) + 1;
            }
            map.put(c, right); // 更新字元最新出現位置
            maxLen = Math.max(maxLen, right - left + 1); // 更新最大長度
        }

        return maxLen;
    }
}


實際操作:

字串:"p w w k e w"
索引: 0 1 2 3 4 5

  • left = 0
  • maxLen = 0
  • 使用 map 記錄每個字元最後一次出現的位置

Step1:
right = 0 → p

  • p 不在 map 中,加入 map:p → 0
  • 視窗為 "p" → 長度 = 1
  • 更新 maxLen = 1

Step2:
right = 1 → w

  • w 不在 map 中,加入 map:w → 1
  • 視窗為 "pw" → 長度 = 2
  • 更新 maxLen = 2

Step3:
right = 2 → w(重複)

  • w 在 map 中,而且 map.get('w') = 1 >= left(0),表示它在目前視窗內,把 left 移到 map.get('w') + 1 = 2 → 視窗起點變到第 2 個索引
  • 更新 w → 2(新位置)
  • 視窗現在是 "w"(從索引 2 開始) → 長度 = 1
  • maxLen 還是 2

Step4:
right = 3 → k

  • k 不在 map 中,加入 map:k → 3
  • 視窗為 "wk" → 長度 = 2
  • maxLen = 2(不變)

Step5:
right = 4 → e

  • e 不在 map 中,加入 map:e → 4
  • 視窗為 "wke" → 長度 = 3
  • 更新 maxLen = 3

Step6:
right = 5 → w(重複)

  • w 在 map 中,map.get('w') = 2 >= left(2),移動 left → map.get('w') + 1 = 3
  • 更新 w → 5
  • 視窗為 "kew" → 長度 = 3
  • maxLen = 3(保持)

結果:maxLen = 3

https://ithelp.ithome.com.tw/upload/images/20251007/20170015p43kvKXXlh.png


上一篇
LeetCode Day22
下一篇
LeetCode Day24
系列文
LeetCode 每日任務24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言